from mmutils import generate_code, apikey, YunPian
from rest_framework.viewsets import ModelViewSet,GenericViewSet
from rest_framework_jwt.serializers import jwt_encode_handler,jwt_payload_handler
from .serializers import *
from django.contrib.auth.backends import ModelBackend
from .models import *
from django.db.models import Q
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import mixins
from utils.permission import IsOwnerOrReadOnly
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication


class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|
                                           Q(mobile=username))
            if user.check_password(password):
                return user
        except:
            return None

class SmsCodeViewSet(ModelViewSet):
    queryset = VerifyCode.objects.all()
    serializer_class = SmsSerializer
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        mobile = serializer.validated_data['mobile']
        code = generate_code(self)
        yunpian = YunPian(apikey)
        sms_status = yunpian.send_sms(code=code,mobile=mobile)
        if sms_status['code']!=0:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        else:
            record = VerifyCode(mobile=mobile, code=code)
            record.save()
            return Response({"mobile":mobile}, status=status.HTTP_201_CREATED)


class UserViewset(mixins.CreateModelMixin, GenericViewSet,mixins.RetrieveModelMixin,
                  mixins.UpdateModelMixin):

    queryset = UserProfile.objects.all()
    # 用户序列化
    # serializer_class = UserRegisterSerializer
    # permission_classes = (IsAuthenticated,IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)

    def get_permissions(self):
        if self.action == 'retrieve':
            return [IsAuthenticated()]
        elif self.action == 'create':
            return []
        return []

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return UserDetailSerializer
        elif self.action == 'create':
            return UserRegisterSerializer
        return UserDetailSerializer


    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        payload = jwt_payload_handler(user)
        re_dict = serializer.data
        re_dict['token'] = jwt_encode_handler(payload)

        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()

    def get_object(self):
        return self.request.user
